package api

import (
	"net/http"

	"github.com/ev-charging/cloud-platform/internal/api/handlers"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// SetupRoutes 设置API路由
func SetupRoutes(router *gin.Engine, deviceHandler *handlers.DeviceHandler, pricingHandler *handlers.PricingHandler) {
	// 配置CORS
	router.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 健康检查路由
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	})

	// API v1 路由组
	v1 := router.Group("/api/v1")
	{
		// 设备相关路由
		devices := v1.Group("/devices")
		{
			devices.GET("/", deviceHandler.ListDevices)
			devices.GET("/:id", deviceHandler.GetDevice)
			devices.POST("/:id/commands", deviceHandler.SendCommand)
			devices.GET("/:id/status", deviceHandler.GetDeviceStatus)
		}

		// 电价相关路由
		pricing := v1.Group("/pricing")
		{
			pricing.GET("/current", pricingHandler.GetCurrentRate)
			pricing.GET("/time-ranges", pricingHandler.GetTimeRanges)
			pricing.POST("/calculate", pricingHandler.CalculateCost)
		}

		// 统计相关路由
		stats := v1.Group("/stats")
		{
			stats.GET("/device-count", deviceHandler.GetDeviceCount)
			stats.GET("/active-devices", deviceHandler.GetActiveDevicesCount)
		}
	}
}